using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Reflection;
using System.IO;

namespace FlexListViewerMOSS.Deploy
{
    public class FlexListFeature : SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb web = (SPWeb)properties.Feature.Parent;

                SPDocumentLibrary list = (SPDocumentLibrary)web.Lists["Web Part Gallery"];

                SPListItem item = list.Items.Add();
                Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("FlexListViewerMOSS.Deploy.FlexListViewer.webpart");


                SPFile file = list.RootFolder.Files.Add("FlexListViewer.webpart", s, true, "", false);
                s.Flush();
                s.Close();


                file.Item.Update();

                file.Update();


            }
            catch (Exception err)
            {
                
                System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
                el.Source = "FlexListFeature activation ";
                el.WriteEntry(err.Message);
            } 
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb web = (SPWeb)properties.Feature.Parent;

                
                SPDocumentLibrary list = (SPDocumentLibrary)web.Lists["Web Part Gallery"];
                //SPQuery query = new SPQuery();
                //query.Query = "<Query><Where><Eq><FieldRef Name=\"LinkFilename\" /><Value Type=\"Computed\">FlexListViewer.webpart</Value></Eq></Where></Query>";

                //SPListItemCollection webparts = list.GetItems(query);

                foreach (SPListItem item in list.Items)
                {
                    if (item["Title"].ToString().Equals("FlexListViewer"))
                        item.Delete();
                }

                list.Update();
            }
            catch (Exception err)
            {
                System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
                el.Source = "FlexListFeature deactivation";
                el.WriteEntry(err.Message);
            }

            
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            return;
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            return;
        }

        
    }
}
